package cc.jq1024.trigger.listener;

import cc.jq1024.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cc.jq1024.domain.strategy.service.IRaffleStock;
import cc.jq1024.types.event.BaseEvent;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 监听 奖品库存耗尽的 MQ 消息
 * @Date: 2024-04-25-21:25
 */
@Slf4j
@Component
public class StrategyAwardStockZeroCustomer {

    @Value("${spring.rabbitmq.topic.strategy_award_stock.zero}")
    private String topic;

    @Resource
    private IRaffleStock raffleStock;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.strategy_award_stock.zero}"))
    public void listener(String message) {
        try {
            log.info("监听活动抽奖奖品库存消耗为0消息 topic: {} message: {}", topic, message);
            // 转换对象
            BaseEvent.EventMessage<StrategyAwardStockKeyVO> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<Long>>() {}.getType());
            StrategyAwardStockKeyVO strategyAwardStockKeyVO = eventMessage.getData();
            // 更新库存
            raffleStock.clearStrategyAwardStock(strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
            // 清空队列 「此时就不需要延迟更新数据库记录了」
            raffleStock.clearQueueValue();
        } catch (Exception e) {
            log.error("监听活动抽奖奖品库存消耗为0消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }

}
